package com.tea.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tea.Model.Dynamic;
import com.tea.Model.DynamicType;
import com.tea.mapper.DynamicMapper;
import com.tea.mapper.DynamicTypeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 商家动态分类服务类
 */
@Service
@Slf4j
public class DynamicTypeService extends ServiceImpl<DynamicTypeMapper, DynamicType> {

    @Resource
    private DynamicTypeMapper dynamicTypeMapper;
    
    @Resource
    private DynamicMapper dynamicMapper;

    /**
     * 获取所有动态分类，按排序字段排序
     * @return 动态分类列表
     */
    public List<DynamicType> listAllTypesOrderBySort() {
        return dynamicTypeMapper.selectAllTypesOrderBySort();
    }

    /**
     * 创建动态分类
     * @param dynamicType 动态分类信息
     * @return 是否创建成功
     */
    public boolean createDynamicType(DynamicType dynamicType) {
        try {
            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            dynamicType.setCreateTime(now);
            dynamicType.setUpdateTime(now);
            
            // 如果没有设置排序，设置为最大值+1
            if (dynamicType.getSortOrder() == null) {
                QueryWrapper<DynamicType> queryWrapper = new QueryWrapper<>();
                queryWrapper.orderByDesc("sort_order").last("LIMIT 1");
                DynamicType lastType = getOne(queryWrapper);
                int nextOrder = (lastType != null && lastType.getSortOrder() != null) ? 
                    lastType.getSortOrder() + 1 : 1;
                dynamicType.setSortOrder(nextOrder);
            }
            
            return save(dynamicType);
        } catch (Exception e) {
            log.error("创建动态分类失败", e);
            return false;
        }
    }

    /**
     * 更新动态分类
     * @param dynamicType 动态分类信息
     * @return 是否更新成功
     */
    public boolean updateDynamicType(DynamicType dynamicType) {
        try {
            // 设置更新时间
            dynamicType.setUpdateTime(LocalDateTime.now());
            return updateById(dynamicType);
        } catch (Exception e) {
            log.error("更新动态分类失败，ID: {}", dynamicType.getDynamicTypeId(), e);
            return false;
        }
    }

    /**
     * 检查分类名称是否已存在
     * @param typeName 分类名称
     * @param excludeId 排除的ID（用于更新时检查）
     * @return 是否存在
     */
    public boolean isTypeNameExists(String typeName, Long excludeId) {
        QueryWrapper<DynamicType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type_name", typeName);
        queryWrapper.eq("deleted", 0);
        if (excludeId != null) {
            queryWrapper.ne("dynamic_type_id", excludeId);
        }
        return count(queryWrapper) > 0;
    }

    /**
     * 检查分类是否被动态使用
     * @param typeId 分类ID
     * @return 是否被使用
     */
    public boolean isTypeInUse(Long typeId) {
        QueryWrapper<Dynamic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type_id", typeId);
        return dynamicMapper.selectCount(queryWrapper) > 0;
    }
}